package com.haixiaoke.saas.enterprise.contract.controller;

import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.ContractConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.ExportUtil;
import com.haixiaoke.saas.contract.domain.ProprietorContract;
import com.haixiaoke.saas.contract.service.IProprietorContractService;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.user.domain.UserConsumer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 业主合同管理Controller
 *
 * @author xiaolong
 * @date 2024-05-27
 */
@RestController
@RequestMapping("/enterprise/contract/proprietorContract")
public class EnterpriseProprietorContractController extends BaseController {
    @Autowired
    private IProprietorContractService proprietorContractService;
    @Autowired
    private IHouseService houseService;

    /**
     * 查询业主合同管理列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:list')")
    @GetMapping("/list")
    @TenantScope
    public TableDataInfo list(ProprietorContract proprietorContract) {
        startPage();
        proprietorContract.setTenantId(TenantContext.getTenantId());
        List<ProprietorContract> list = proprietorContractService.selectProprietorContractList(proprietorContract);
        return getDataTable(list);
    }

    /**
     * 获取业主合同管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:query')")
    @GetMapping(value = "/{proprietorContractId}")
    public AjaxResult getInfo(@PathVariable("proprietorContractId") String proprietorContractId) {
        return success(proprietorContractService.selectProprietorContractByProprietorContractId(proprietorContractId));
    }

    /**
     * 获取预览电子合同内容链接
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:query')")
    @PostMapping(value = "/previewUrl")
    public AjaxResult electronicVisaPreviewUrl(@RequestBody ProprietorContract proprietorContract) {
        return AjaxResult.success("操作成功", proprietorContractService.selectProprietorContractElectronicVisaPreviewUrl(proprietorContract));
    }

    /**
     * 新增业主合同管理
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:add')")
    @PostMapping
    @TenantScope
    @RepeatSubmit
    public AjaxResult add(@RequestBody ProprietorContract proprietorContract) {
        proprietorContract.setTenantId(TenantContext.getTenantId());
        proprietorContract.setCreateBy(getLoginUser().getUserId().toString());
        House house = proprietorContract.getHouse();
        house.setCooperationType(proprietorContract.getCooperationType());
        if (houseService.checkHouse(house)) {
            return AjaxResult.error("该房屋已存在");
        }
        Long userId = getUserId();
        house.setCreateBy(String.valueOf(userId));
        house.setOperatorId(userId);
        house.setTenantId(TenantContext.getTenantId());
        LoginUser loginUser = getLoginUser();
        house.setBizUserBusiness(loginUser.getBizUser());
        return toAjax(proprietorContractService.insertProprietorContract(proprietorContract));
    }

    /**
     * 修改业主合同管理
     */
    @PreAuthorize("@ss.hasPermi('business:proprietorContract:edit')")
    @PutMapping
    @TenantScope
    @RepeatSubmit
    public AjaxResult edit(@RequestBody ProprietorContract proprietorContract) {
        ProprietorContract byProprietorContractId = proprietorContractService.selectProprietorContractByProprietorContractId(proprietorContract.getProprietorContractId());
        if (!TenantContext.getTenantId().equals(byProprietorContractId.getTenantId())) {
            return AjaxResult.error("不能修改其他租户的合同信息");
        }
        proprietorContract.setTenantId(TenantContext.getTenantId());
        proprietorContract.setUpdateBy(getLoginUser().getUserId().toString());
        return toAjax(proprietorContractService.updateProprietorContract(proprietorContract));
    }

    /**
     * 删除业主合同管理
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:remove')")
    @DeleteMapping("/{proprietorContractIds}")
    @TenantScope
    @RepeatSubmit
    public AjaxResult remove(@PathVariable String[] proprietorContractIds) {
        return toAjax(proprietorContractService.deleteProprietorContractByProprietorContractIds(proprietorContractIds));
    }


    /**
     * 获取业主信息
     */
    @GetMapping("/proprietorInfo")
    @TenantScope
    public TableDataInfo proprietorInfo() {
        startPage();
        List<UserConsumer> list = proprietorContractService.selectProprietorInfo();
        return getDataTable(list);
    }

    /**
     * 上传确认合同
     *
     * @param proprietorContract
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:upload')")
    @Log(title = "业主合同上传合同", businessType = BusinessType.UPDATE)
    @PutMapping("/uploadContractImage")
    public AjaxResult uploadContractImage(@RequestBody ProprietorContract proprietorContract) {
        proprietorContract.setUpdateBy(getUsername());
        return proprietorContractService.uploadContractImage(proprietorContract);
    }

    /**
     * 合同撤销
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:repeal')")
    @Log(title = "租客合同撤销", businessType = BusinessType.UPDATE)
    @PutMapping("/repeal")
    public AjaxResult repeal(@RequestBody ProprietorContract contract) {
        contract.setUpdateBy(getUsername());
        return proprietorContractService.repealProprietorContract(contract);
    }

    /**
     * 签署合同
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:signing')")
    @Log(title = "租客合同签署", businessType = BusinessType.UPDATE)
    @PutMapping("/signing")
    @TenantScope
    public AjaxResult lesseesSigning(@RequestBody ProprietorContract proprietorContract) {
        proprietorContract.setTenantId(TenantContext.getTenantId());
        return proprietorContractService.signingLesseeContract(proprietorContract, null);
    }

    /**
     * 导出租客合同列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:proprietorContract:export')")
    @Log(title = "租客合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public ResponseEntity<byte[]> export(HttpServletResponse response, ProprietorContract proprietorContract) {
        ProprietorContract contract = proprietorContractService.selectProprietorContractByProprietorContractId(proprietorContract.getProprietorContractId());
        if (ObjectUtil.isEmpty(contract) || !ContractConstants.SIGNING_MODE_PAPER.equals(contract.getSigningMode())) {
            throw new ServiceException("合同不存在或非电子合同，无法导出");
        }

        // 创建一个空的Word文档
        try {
            byte[] documentBytes = ExportUtil.generateWordDocument(contract.getContractContent());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "formatted_document.docx");
            headers.setContentLength(documentBytes.length);

            return new ResponseEntity<>(documentBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            throw new ServiceException("导出失败：" + e.getMessage());
        }
    }
}
